const UserModel = require('../models/User');
const Video = require('../models/Video');
const Like = require('../models/Like');
const Favorite = require('../models/Favorite');
const { sequelize } = require('../config/db');

/**
 * 用户控制器类
 * 处理用户相关的API请求
 */
class UserController {
  /**
   * 获取当前登录用户的信息
   * @param {object} req - Express请求对象
   * @param {object} res - Express响应对象
   */
  async getMyInfo(req, res) {
    try {
      const userId = req.user.id;
      const user = await UserModel.findByPk(userId);
      
      if (!user) {
        return res.status(404).json({
          code: 404,
          message: '用户不存在',
          data: null
        });
      }
      
      // 不返回敏感信息
      const userInfo = {
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        role: user.role,
        status: user.status,
        created_at: user.created_at,
        updated_at: user.updated_at
      };
      
      return res.status(200).json({
        code: 200,
        message: '获取用户信息成功',
        data: userInfo
      });
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return res.status(500).json({
        code: 500,
        message: '获取用户信息失败，请稍后重试',
        data: null
      });
    }
  }
  
  /**
   * 编辑当前登录用户的信息
   * @param {object} req - Express请求对象
   * @param {object} res - Express响应对象
   */
  async updateMyInfo(req, res) {
    try {
      const userId = req.user.id;
      const { nickname, avatar } = req.body;
      
      const user = await UserModel.findByPk(userId);
      
      if (!user) {
        return res.status(404).json({
          code: 404,
          message: '用户不存在',
          data: null
        });
      }
      
      // 更新用户信息
      const updateData = {};
      if (nickname !== undefined) updateData.nickname = nickname;
      if (avatar !== undefined) updateData.avatar = avatar;
      updateData.updated_at = new Date();
      
      await user.update(updateData);
      
      // 返回更新后的用户信息
      const updatedUser = {
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        role: user.role,
        status: user.status,
        created_at: user.created_at,
        updated_at: user.updated_at
      };
      
      return res.status(200).json({
        code: 200,
        message: '更新用户信息成功',
        data: updatedUser
      });
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return res.status(500).json({
        code: 500,
        message: '更新用户信息失败，请稍后重试',
        data: null
      });
    }
  }
  
  /**
   * 获取当前登录用户的统计信息
   * @param {object} req - Express请求对象
   * @param {object} res - Express响应对象
   */
  async getMyStats(req, res) {
    try {
      const userId = req?.user?.id;
      
      // 分别获取各项统计数据，避免一个失败影响全部
      let likeCount = 0;
      let fanCount = 0;
      let likedCount = 0;
      
      // 获取用户点赞的视频数量
      try {
        // 直接使用SQL查询代替可能不存在的count方法
        const likeResult = await sequelize.query(
          `SELECT COUNT(*) as count FROM likes WHERE user_id = :userId`,
          {
            replacements: { userId },
            type: sequelize.QueryTypes.SELECT
          }
        );
        likeCount = likeResult?.[0]?.count || 0;
      } catch (e) {
        console.error('获取用户点赞数失败:', e);
        likeCount = 0;
      }
      
      // 获取用户的粉丝数量
      try {
        const fanResult = await sequelize.query(
          `SELECT COUNT(*) as count FROM user_follow WHERE follower_id = :userId`,
          {
            replacements: { userId },
            type: sequelize.QueryTypes.SELECT
          }
        );
        fanCount = fanResult?.[0]?.count || 0;
      } catch (e) {
        console.error('获取用户粉丝数失败:', e);
        fanCount = 0;
      }
      
      // 获取用户发布的视频获得的点赞总数
      try {
        const likedResult = await sequelize.query(
          `SELECT COUNT(*) as count 
           FROM likes 
           WHERE video_id IN (SELECT id FROM videos WHERE user_id = :userId)`,
          {
            replacements: { userId },
            type: sequelize.QueryTypes.SELECT
          }
        );
        likedCount = likedResult?.[0]?.count || 0;
      } catch (e) {
        console.error('获取用户视频点赞总数失败:', e);
        likedCount = 0;
      }
      
      const stats = {
        likeCount: likeCount,      // 用户点赞的视频数量
        followerCount: fanCount,   // 用户的粉丝数量
        videoLikeCount: likedCount // 用户发布的视频获得的点赞总数
      };
      
      return res.status(200).json({
        code: 200,
        message: '获取用户统计信息成功',
        data: stats
      });
    } catch (error) {
      console.error('获取用户统计信息失败:', error);
      return res.status(500).json({
        code: 500,
        message: '获取用户统计信息失败，请稍后重试',
        data: null
      });
    }
  }
  
  /**
   * 获取当前登录用户发布的视频列表
   * @param {object} req - Express请求对象
   * @param {object} res - Express响应对象
   */
  async getMyVideos(req, res) {
    try {
      const userId = req?.user?.id;
      const page = parseInt(req?.query?.page) || 1;
      const pageSize = parseInt(req?.query?.pageSize) || 10;
      
      // 验证分页参数
      if (page < 1 || pageSize < 1 || pageSize > 100) {
        return res.status(400).json({
          code: 400,
          message: '无效的分页参数',
          data: null
        });
      }
      
      const offset = (page - 1) * pageSize;
      
      // 使用videos_detail视图查询视频详情
      const query = `
        SELECT * FROM videos_detail 
        WHERE status = 1 AND user_id = :userId 
        ORDER BY created_at DESC 
        LIMIT :pageSize OFFSET :offset
      `;
      
      let results = [];
      try {
        results = await sequelize.query(query, {
          replacements: { userId, pageSize, offset },
          type: sequelize.QueryTypes.SELECT
        });
        // 确保结果是数组
        if (!Array.isArray(results)) {
          results = [];
        }
      } catch (e) {
        console.error('获取视频列表失败:', e);
        results = [];
      }
      
      // 获取总数
      let total = 0;
      try {
        const countResult = await sequelize.query(
          `SELECT COUNT(*) as total FROM videos_detail WHERE status = 1 AND user_id = :userId`,
          {
            replacements: { userId },
            type: sequelize.QueryTypes.SELECT
          }
        );
        total = countResult?.[0]?.total || 0;
      } catch (e) {
        console.error('获取视频总数失败:', e);
        total = 0;
      }
      
      return res.status(200).json({
        code: 200,
        message: '获取用户视频列表成功',
        data: {
          videos: results,
          total,
          page,
          pageSize
        }
      });
    } catch (error) {
      console.error('获取用户视频列表失败:', error);
      return res.status(500).json({
        code: 500,
        message: '获取用户视频列表失败，请稍后重试',
        data: null
      });
    }
  }
  
  /**
   * 获取当前登录用户收藏的视频列表
   * @param {object} req - Express请求对象
   * @param {object} res - Express响应对象
   */
  async getMyFavorites(req, res) {
    try {
      const userId = req?.user?.id;
      const page = parseInt(req?.query?.page) || 1;
      const pageSize = parseInt(req?.query?.pageSize) || 10;
      
      // 验证分页参数
      if (page < 1 || pageSize < 1 || pageSize > 100) {
        return res.status(400).json({
          code: 400,
          message: '无效的分页参数',
          data: null
        });
      }
      
      // 初始化变量为默认值
      let favoriteVideoIds = [];
      let total = 0;
      let favorites = [];
      
      try {
        // 获取用户收藏的视频ID列表
        favoriteVideoIds = await Favorite.getUserFavoriteVideos(userId, page, pageSize) || [];
        // 确保是数组
        if (!Array.isArray(favoriteVideoIds)) {
          favoriteVideoIds = [];
        }
      } catch (e) {
        console.error('获取收藏视频ID失败:', e);
      }
      
      try {
        // 获取总数
        const countResult = await sequelize.query(
          `SELECT COUNT(*) as total FROM favorate WHERE user_id = :userId`,
          {
            replacements: { userId },
            type: sequelize.QueryTypes.SELECT
          }
        );
        total = countResult?.[0]?.total || 0;
      } catch (e) {
        console.error('获取收藏总数失败:', e);
      }
      
      // 如果有收藏的视频ID，获取视频详情
      if (favoriteVideoIds.length > 0) {
        try {
          // 使用videos_detail视图查询视频详情
          const query = `
            SELECT * FROM videos_detail 
            WHERE status = 1 AND id IN (:videoIds)
          `;
          
          const results = await sequelize.query(query, {
            replacements: { videoIds: favoriteVideoIds },
            type: sequelize.QueryTypes.SELECT
          });
          
          // 创建ID到视频的映射，以保持原始顺序
          const videoMap = new Map();
          if (Array.isArray(results)) {
            results.forEach(video => {
              if (video && video.id) {
                videoMap.set(video.id, video);
              }
            });
          }
          
          // 按照收藏ID的顺序排列视频
          favorites = favoriteVideoIds
            .map(id => videoMap.get(id))
            .filter(video => video !== undefined);
        } catch (e) {
          console.error('获取视频详情失败:', e);
          favorites = [];
        }
      }
      
      return res.status(200).json({
        code: 200,
        message: '获取收藏视频列表成功',
        data: {
          favorites,
          total,
          page,
          pageSize
        }
      });
    } catch (error) {
      console.error('获取收藏视频列表失败:', error);
      return res.status(500).json({
        code: 500,
        message: '获取收藏视频列表失败，请稍后重试',
        data: null
      });
    }
  }
  
  /**
   * 获取当前登录用户点赞的视频列表
   * @param {object} req - Express请求对象
   * @param {object} res - Express响应对象
   */
  async getMyLikes(req, res) {
    try {
      const userId = req?.user?.id;
      const page = parseInt(req?.query?.page) || 1;
      const pageSize = parseInt(req?.query?.pageSize) || 10;
      
      // 验证分页参数
      if (page < 1 || pageSize < 1 || pageSize > 100) {
        return res.status(400).json({
          code: 400,
          message: '无效的分页参数',
          data: null
        });
      }
      
      // 初始化变量为默认值
      let likedVideoIds = [];
      let total = 0;
      let likes = [];
      
      try {
        // 获取用户点赞的视频ID列表
        likedVideoIds = await Like.getUserLikedVideos(userId, page, pageSize) || [];
        // 确保是数组
        if (!Array.isArray(likedVideoIds)) {
          likedVideoIds = [];
        }
      } catch (e) {
        console.error('获取点赞视频ID失败:', e);
      }
      
      try {
        // 获取总数
        const countResult = await sequelize.query(
          `SELECT COUNT(*) as total FROM likes WHERE user_id = :userId`,
          {
            replacements: { userId },
            type: sequelize.QueryTypes.SELECT
          }
        );
        total = countResult?.[0]?.total || 0;
      } catch (e) {
        console.error('获取点赞总数失败:', e);
      }
      
      // 如果有点赞的视频ID，获取视频详情
      if (likedVideoIds.length > 0) {
        try {
          // 使用videos_detail视图查询视频详情
          const query = `
            SELECT * FROM videos_detail 
            WHERE status = 1 AND id IN (:videoIds)
          `;
          
          const results = await sequelize.query(query, {
            replacements: { videoIds: likedVideoIds },
            type: sequelize.QueryTypes.SELECT
          });
          
          // 创建ID到视频的映射，以保持原始顺序
          const videoMap = new Map();
          if (Array.isArray(results)) {
            results.forEach(video => {
              if (video && video.id) {
                videoMap.set(video.id, video);
              }
            });
          }
          
          // 按照点赞ID的顺序排列视频
          likes = likedVideoIds
            .map(id => videoMap.get(id))
            .filter(video => video !== undefined);
        } catch (e) {
          console.error('获取视频详情失败:', e);
          likes = [];
        }
      }
      
      return res.status(200).json({
        code: 200,
        message: '获取点赞视频列表成功',
        data: {
          likes,
          total,
          page,
          pageSize
        }
      });
    } catch (error) {
      console.error('获取点赞视频列表失败:', error);
      return res.status(500).json({
        code: 500,
        message: '获取点赞视频列表失败，请稍后重试',
        data: null
      });
    }
  }
}

module.exports = new UserController();